/**
 * 登录模块，提供登录相关业务功能
 * 
 * @Date: 2015-6-16
 * @author: Jackson wang
 * @version: 1.0
 * @since: 1.0
 */
define(["jquery","sysmanMain", "msgServ","ajaxServ","datagridServ","bizProto","btnServ","jobroleEdit"], 
	function($,sysmanMain,msgServ,ajaxServ,datagridServ,bizProto,btnServ,jobroleEdit) {

	'use strict';

	var    $user,$role,$panel,_bizProto,$dept,
		   deptTreeUrl = "/department/query/getTreeList.action",
		   findUserRoleUrl = "/userRole/findRoleByUserid.action",findUserRoleQueryUrl,
		   findJobRoleUrl = '/jobrole/query/getJobRoleByUseridListDomain.action',findJobRoleQueryUrl,
	       saveUrl = "/userRole/save.action",userRoleSaveUrl,
	       
	       jobroleDelUrl = '/jobrole/del.action',
	       
	       //岗位角色编辑页面url
		   jobroleEditUrl = '/jobrole/query/editPage.action',
	       
	       findRoleUrl = '/role/query/getListDomain.action',findRoleQueryUrl,
	       findUserUrl = "/user/query/getListDomainByDeptid.action",findUserQueryUrl,
	       rootid = 'panel-roleAssign',
	       
	       role_code ={
	       		system:'system',
	       		job:'job'
	       },
	       role_type=role_code.system,
	       
	       //部门列表初始化标志
	       deptInitializd,
	       
	       
	       window_id = 'role-edit-win',
	       
	       //编辑页面初始化设置
			window_width = 600,
			window_height= 400,
	       
	       //当前选中部门及人员
	       curDept,curUser
    
	var	private_method = {
		init : function(doc) {
			if (window.console) {
			console.info('userrole modules gets ready and been loaded.');
			}
			_bizProto = new bizProto({doc:doc,rootId:'panel-roleAssign',panelSelector:'div.well',subSystemCode:'sysman',moduleCode:'userRole'});			
			_bizProto.gridHeight -= 15
			
			
			private_method.initPath();
			private_method.initElement(_bizProto.pageDoc)
		},
		
		//初始化路径
		initPath:function(){
			
			findUserRoleQueryUrl = _bizProto.rootPath + findUserRoleUrl;
			userRoleSaveUrl = _bizProto.rootPath +saveUrl;
			findRoleQueryUrl = _bizProto.rootPath + findRoleUrl;
			findJobRoleQueryUrl = _bizProto.rootPath + findJobRoleUrl;
		},
		initElement: function (doc) {
			deptInitializd = false;
			//初始化部门和用户
			private_method.initDeptUser();				
			
			//初始化角色
			private_method.initRoleGrid();
			
			//绑定click事件
			var $btn = $('#'+rootid+ ' a.easyui-linkbutton')
			
			$($btn).unbind('click');
			$($btn).bind('click',private_method.function_btn_listenner)
			$.messager.progress('close');
		},
		// 功能按钮监听函数
		function_btn_listenner : function(e) {
			var _buttonConfig = {
				'系统角色':function(e){private_method.typeClick({type:role_code.system,evt:e})},
				'岗位角色':function(e){private_method.typeClick({type:role_code.job,evt:e})},
				'保存设置':private_method.saveUserRoles,
				'新增':private_method.add,
				'编辑':private_method.edit,
				'删除':private_method.del
			}
			btnServ.applyButton({buttonEvt:e,buttonConfig:_buttonConfig})

		},
		/**
		 * 评价类型监听事件
		 * @param _options.type	评价类型
		 * @param _options.evt	按钮事件
		 */
		typeClick:function(_options){
			role_type = _options.type
			private_method.initDeptUser();
			private_method.initRoleGrid(_options)
			if(_options.evt && _options.evt.currentTarget){
				$(_options.evt.currentTarget).linkbutton('enable')
			}
		},
		
		/**
		 * 初始化角色列表(tree)
		 * 
		 */
		initRoleGrid:function(_options){
			
				
				var  param = {
							width : 'auto',						
							pagination:true,
							border:true,
							rownumbers:true,
							fitColumns : true,
							singleSelect:false,
							striped:true,
							idField: 'id',
							height : _bizProto.gridHeight,							
							toolbar:'#'+rootid+' div.tb-role'
						}
						
				var _url ,_param={}
				switch(role_type){
					
					case role_code.system:
						_param.columns =[[
								{field:'ck',checkbox:true},
								{field:'id',title:'编号',width:20,halign:'center'},
								{field:'name',title:'角色名称',width:60,halign:'center'}								
							]]
						_url = findRoleQueryUrl
						break;
					case role_code.job:
						_url =findJobRoleQueryUrl
						
						_param.columns=[[
							{field:'ck',checkbox:true},
							{field:'id',title:'编号',width:20,halign:'center'},
							{field:'deptid',title:'部门编码',width:20,halign:'center'},
							{field:'deptname',title:'部门名称',width:20,halign:'center'},
							{field:'jobname',title:'角色名称',width:60,halign:'center'}
						]]
						break;
					default:
						_param.url = findRoleQueryUrl
				}
				if(_url){
					_param.url =_url
				}
				$role = $('#'+rootid + ' div.dg-role');
				_param = $.extend({},param,_param);
				
				$($role).datagrid(_param);
			
		},
		/**
		 * 初始化部门人员
		 * @param _options.bizProto
		 */
		initDeptUser:function(){
			$dept = $('#'+rootid + ' div.tg-department');
			
			
			//部门信息
			if($dept && $dept.length>0){
				if(!deptInitializd){
					$dept.treegrid({
						rownumbers:true,
						animate: true,
						idField: 'id',
						treeField: 'name',
						striped:true,
						border:true,
						fitColumns: true,
						height : _bizProto.gridHeight,
						url : _bizProto.rootPath + deptTreeUrl,
						onClickRow:private_method.getUsers,
						columns:[[						
							{field:'name',title:'部门名称',width:60,halign:'center'}									
						]],
						toolbar:'#'+rootid +' div.tb-depart'
					})
				}
				
				deptInitializd = true
			}
			
			//用户信息
			$user = $('#'+rootid + " div.dg-user");
			$user.datagrid({
				rownumbers:true,
				animate: true,
				idField: 'id',
				treeField: 'name',
				striped:true,
				border:true,
				fitColumns: true,
				pagination:true,
				height : _bizProto.gridHeight,
				toolbar:'#'+rootid +' div.tb-user',
				onClickRow:private_method.getRoles,
				columns:[[
					{field:'id',title:'编号',width:20,halign:'center'},
					{field:'name',title:'用户姓名',width:60,halign:'center'},
					{field:'jobname',title:'岗位名称',width:60,halign:'center'}
				]]
			})
			
			$role = $('#'+rootid + " div.dg-role");
			$($role).datagrid({data:[]})
		},
		searchFunction:function(value,name){
			var _param = {}
	    	_param['searchName'] = name;_param['searchValue'] = value
	    	return _param;
		},
		getUsers:function(data){
			curDept = data;
			$user = $('#'+rootid +" div.dg-user");
			if($user &&　$user.length>0){
				var _options = $user.datagrid('options')
				if(_options && _options.url){
					$user.datagrid('load',{deptid:data.id})
				}else{
					$user.datagrid({
						height : _bizProto.gridHeight,
						url : _bizProto.rootPath + findUserUrl,
						onClickRow:private_method.getRoles,
						queryParams:{deptid:data.id}
					});
				}
			
			}
		},
		 getRoles:function (rowIndex, rowData){
		 	curUser = rowData
		 	
		 	switch(role_type){
		 		case role_code.system:
		 			$.post(findUserRoleQueryUrl, {userid:rowData.id}, function(rsp) {
						 $role.datagrid("unselectAll");
					 if(rsp.length!=0){
						 $.each(rsp,function(i,e){
							 $role.datagrid("selectRecord",e.roleid);
						 });
					 }else{
					 	msgServ.Msgslide('该用户暂无角色');					
					 }
					}, "JSON").error(function() {
						msgServ.Msgslide('获取用户角色失败');					 
					});
		 		break;
		 		case role_code.job:
			 		
					if(curUser && curUser.id){
						$role = $('#'+rootid + " div.dg-role");
						$($role).datagrid('load',{userid:curUser.id})
					}
					break;
					
		 	}
		 	
		},
		saveUserRoles:function (e){
			 var selectRow=curUser;
			 var selectRows=$role.datagrid("getSelections");
			 var isCheckedIds
			 
			 if(selectRows){
				 isCheckedIds=datagridServ.getCheckedIds({target:$role});				 
			 }
			 if(selectRow){
			 	var _param = {userid:selectRow.id,roleid:isCheckedIds}
			 	ajaxServ.runAjax({
					url:userRoleSaveUrl,
				 	contentType:'form',
				 	data:_param,
				 	callback:function(data){
				 		msgServ.Msgslide('保存人员角色成功！');
				 		if(e && e.currentTarget){
				 			$(e.currentTarget).linkbutton('enable')
				 		}
				 	}
				 	,
				 	error:function(){
				 		if(e && e.currentTarget){
				 			$(e.currentTarget).linkbutton('enable')
				 		}
				 	}
				})
				
			 }else{
				 msgServ.Msgslide('请选择人员及角色');
				 if(e && e.currentTarget){
		 			$(e.currentTarget).linkbutton('enable')
		 		}
			 }			
		 },
		 add:function(e){
		 	var _data = {}
		 	
		 	switch(role_type){
		 		case role_code.system:
		 			break;
		 		case role_code.job:
		 			if( curDept && curUser){
		 				var _data = {
		 					userid:curUser.id,
		 					username:curUser.name,
		 					deptid:curDept.id,
		 					deptname:curDept.name
		 				}
		 				jobroleEdit.openPage({data:_data})
		 			}else{
		 				msgServ.Msgslide('请先选择用户!')
		 				return
		 			}
		 	}
		 	
		 	if(e && e.currentTarget){
	 			$(e.currentTarget).linkbutton('enable')
	 		}
		 },
		 edit:function(e){
		 	var rootpath = '/'+sysmanMain.getRootPath();
		 	switch(role_type){
		 		case role_code.job:		 		
 				var records = $($role).datagrid('getSelections')
 				if(records.length==1){
 					var _data = {
	 					userid:curUser.id,
	 					username:curUser.name,
	 					deptid:curDept.id,
	 					deptname:curDept.name
	 				}
	 				var _param = $.extend(_data,records[0])
	 				jobroleEdit.openPage({data:_param})
 				}else{
 					msgServ.Msgslide('请选择要编辑的角色!')
 				} 				 		
		 		break;
		 	}
		 	if(e && e.currentTarget){
	 			$(e.currentTarget).linkbutton('enable')
	 		}
		 },
		 del : function(e) {			
			
			$role= $('#'+rootid +" div.dg-role");
			var _url = '/'+sysmanMain.getRootPath()+jobroleDelUrl;
			datagridServ.delRow({url:_url,target:$role,auditEnable:false,evt:e});			
		}
	}
	
	var public_method = {
		init:function(doc){
			private_method.init(doc)
		}
	}	
	return public_method;
});